'use strict';
const db = uniCloud.database();
const recordCollection = db.collection('crop_records');
const cropCollection = db.collection('crops');

exports.main = async (event, context) => {
  const { action, data, uniIdToken, userId } = event;
  
  // 获取当前用户ID
  let uid;
  
  // 检查是否有uniIdToken（从拦截器传入）
  if (uniIdToken) {
    try {
      // 解析token
      const tokenObj = JSON.parse(uniIdToken);
      uid = tokenObj.uid;
    } catch (error) {
      console.error('解析token失败:', error);
    }
  }
  
  // 如果没有从token中获取到uid，尝试从context.auth中获取
  if (!uid && context.auth) {
    uid = context.auth.uid;
  }
  
  // 如果仍然没有uid，尝试使用传入的userId
  if (!uid && userId) {
    uid = userId;
  }
  
  // 如果仍然没有uid，返回未授权错误
  if (!uid) {
    return {
      code: 401,
      msg: '未授权'
    };
  }
  
  switch (action) {
    case 'add':
      return await addRecord(data, uid);
    case 'update':
      return await updateRecord(data, uid);
    case 'delete':
      return await deleteRecord(data.id, uid);
    case 'get':
      return await getRecord(data.id, uid);
    case 'list':
      return await listRecords(data, uid);
    default:
      return {
        code: 400,
        msg: '无效的操作'
      };
  }
};

// 添加生长记录
async function addRecord(data, uid) {
  try {
    // 验证农作物是否存在且属于当前用户
    const crop = await cropCollection.doc(data.crop_id).get();
    if (!crop.data || crop.data.length === 0) {
      return {
        code: 404,
        msg: '农作物不存在'
      };
    }
    
    if (crop.data[0].user_id !== uid) {
      return {
        code: 403,
        msg: '无权操作此农作物'
      };
    }
    
    // 添加用户ID
    data.user_id = uid;
    
    // 转换日期字符串为时间戳
    if (data.record_date) {
      data.record_date = new Date(data.record_date).getTime();
    }
    
    const result = await recordCollection.add(data);
    
    return {
      code: 200,
      msg: '添加成功',
      data: result
    };
  } catch (error) {
    return {
      code: 500,
      msg: '添加失败',
      error: error.message
    };
  }
}

// 更新生长记录
async function updateRecord(data, uid) {
  try {
    const id = data._id;
    delete data._id; // 移除_id，避免更新时报错
    
    // 转换日期字符串为时间戳
    if (data.record_date) {
      data.record_date = new Date(data.record_date).getTime();
    }
    
    // 更新时间
    data.update_date = Date.now();
    
    // 确认该记录属于当前用户
    const record = await recordCollection.doc(id).get();
    if (!record.data || record.data.length === 0 || record.data[0].user_id !== uid) {
      return {
        code: 403,
        msg: '无权操作此记录'
      };
    }
    
    await recordCollection.doc(id).update(data);
    
    return {
      code: 200,
      msg: '更新成功'
    };
  } catch (error) {
    return {
      code: 500,
      msg: '更新失败',
      error: error.message
    };
  }
}

// 删除生长记录
async function deleteRecord(id, uid) {
  try {
    // 确认该记录属于当前用户
    const record = await recordCollection.doc(id).get();
    if (!record.data || record.data.length === 0 || record.data[0].user_id !== uid) {
      return {
        code: 403,
        msg: '无权操作此记录'
      };
    }
    
    await recordCollection.doc(id).remove();
    
    return {
      code: 200,
      msg: '删除成功'
    };
  } catch (error) {
    return {
      code: 500,
      msg: '删除失败',
      error: error.message
    };
  }
}

// 获取单个生长记录详情
async function getRecord(id, uid) {
  try {
    const result = await recordCollection.doc(id).get();
    
    if (!result.data || result.data.length === 0) {
      return {
        code: 404,
        msg: '记录不存在'
      };
    }
    
    const record = result.data[0];
    
    // 检查权限
    if (record.user_id !== uid) {
      return {
        code: 403,
        msg: '无权查看此记录'
      };
    }
    
    return {
      code: 200,
      msg: '获取成功',
      data: record
    };
  } catch (error) {
    return {
      code: 500,
      msg: '获取失败',
      error: error.message
    };
  }
}

// 获取生长记录列表
async function listRecords(params, uid) {
  try {
    const { page = 1, pageSize = 10, crop_id, start_date, end_date, growth_stage } = params;
    
    let query = recordCollection.where({
      user_id: uid
    });
    
    // 添加筛选条件
    if (crop_id) {
      query = query.where({
        crop_id: crop_id
      });
    }
    
    if (growth_stage) {
      query = query.where({
        growth_stage: growth_stage
      });
    }
    
    // 日期范围筛选
    if (start_date && end_date) {
      const startTimestamp = new Date(start_date).getTime();
      const endTimestamp = new Date(end_date).getTime();
      
      query = query.where({
        record_date: db.command.gte(startTimestamp).and(db.command.lte(endTimestamp))
      });
    } else if (start_date) {
      const startTimestamp = new Date(start_date).getTime();
      query = query.where({
        record_date: db.command.gte(startTimestamp)
      });
    } else if (end_date) {
      const endTimestamp = new Date(end_date).getTime();
      query = query.where({
        record_date: db.command.lte(endTimestamp)
      });
    }
    
    // 计算总数
    const countResult = await query.count();
    const total = countResult.total;
    
    // 分页查询
    const result = await query
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .orderBy('record_date', 'desc')
      .get();
    
    return {
      code: 200,
      msg: '获取成功',
      data: {
        list: result.data,
        pagination: {
          page,
          pageSize,
          total
        }
      }
    };
  } catch (error) {
    return {
      code: 500,
      msg: '获取失败',
      error: error.message
    };
  }
} 